package com.uhylab.uhuvinetest.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.UHApplication;
import com.uhylab.uhuvinetest.activity.UHDiseaseHistoryActivity;
import com.uhylab.uhuvinetest.activity.UHFeedbackActivity;
import com.uhylab.uhuvinetest.activity.UHLogonActivity;
import com.uhylab.uhuvinetest.activity.UHSettingActivity;
import com.uhylab.uhuvinetest.activity.UHUserInformationActivity;
import com.uhylab.uhuvinetest.activity.UHUserPregnancyActivity;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.base.UHBaseFragment;
import com.uhylab.uhuvinetest.bean.Dataee;
import com.uhylab.uhuvinetest.dao.DaoSingleton;
import com.uhylab.uhuvinetest.dao.UserDataEntity;
import com.uhylab.uhuvinetest.dao.UserDataEntityDao;
import com.uhylab.uhuvinetest.utils.VolleySingleton;
import com.uhylab.uhuvinetest.utils.sharedpreutils.SharedPreUtils;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xyb on 15/12/4 at UHylab
 * 修改日期 : 2016/5/25 at UHylab
 *
 * @version 1.0
 */
public class UHUserCenterFragment extends UHBaseFragment implements View.OnClickListener {
    private TextView BMI;
    private AutoRelativeLayout user_setting_re, user_opinion_re, user_icon_re, user_disease_re, user_pregnancy_re, user_birthday_re, user_six_re, user_wight_re, user_height_re;
    private TextView user_pregnancy_exchange, user_birthday_exchange, user_sex_exchange, user_weight_exchange, user_height_exchange;
    private ArrayList<Integer> user_weight_Items = new ArrayList<Integer>();
    private ArrayList<String> user_sex_Items = new ArrayList<String>();
    private ArrayList<Integer> user_height_Items = new ArrayList<Integer>();
    private TimePickerView pvTime;
    private OptionsPickerView user_sex;
    private OptionsPickerView user_height;
    private OptionsPickerView user_wight;
    //    private OptionsPickerView user_wight;
    //控制时间范围
    Calendar calendar;
    boolean isLogin;
    private VolleySingleton volleySingleton;
    private String sex, name, tel, date, weight, height;
    private Date cloudDate;
    private UserDataEntityDao userDataEntityDao;
    private TextView user_login, user_bmi_exchange;
    private View mView;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void initData() {
        volleySingleton = VolleySingleton.getVolleySingleton(UHApplication.gainContext());
        userDataEntityDao = DaoSingleton.getInstance().getUserDataEntityDao();
        user_icon_re.setOnClickListener(this);
        user_opinion_re.setOnClickListener(this);
        user_setting_re.setOnClickListener(this);
        user_disease_re.setOnClickListener(this);
        user_pregnancy_re.setOnClickListener(this);
        user_birthday_re.setOnClickListener(this);
        user_six_re.setOnClickListener(this);
        user_wight_re.setOnClickListener(this);
        user_height_re.setOnClickListener(this);
        BMI.setOnClickListener(this);
        if (isLogin) {
        } else {
            user_login.setText("点击登陆");
            user_bmi_exchange.setText("");
            user_pregnancy_exchange.setText("");
            user_birthday_exchange.setText("");
            user_weight_exchange.setText("");
            user_height_exchange.setText("");
            user_sex_exchange.setText("");
        }


        //时间选择器
        pvTime = new TimePickerView(mActivity, TimePickerView.Type.YEAR_MONTH_DAY);
        //选项选择器
        user_wight = new OptionsPickerView(mActivity);
        user_sex = new OptionsPickerView(mActivity);
        user_height = new OptionsPickerView(mActivity);
        //控制时间范围
        calendar = Calendar.getInstance();
        for (int i = 30; i < 200; i++) {
            user_weight_Items.add(i);
        }
        for (int i = 100; i < 250; i++) {
            user_height_Items.add(i);
        }
        user_sex_Items.add("男");
        user_sex_Items.add("女");
        user_sex.setPicker(user_sex_Items);
        user_sex.setCyclic(false);
        user_sex.setTitle("请选择性别");
        user_sex.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                sex = user_sex_Items.get(options1).toString();
                if (("男").equals(sex)) {
                    user_sex_exchange.setText(sex);
                    sex = "M";
                    user_pregnancy_re.setVisibility(View.GONE);
                    mView.setVisibility(View.GONE);
                } else {
                    user_sex_exchange.setText(sex);
                    sex = "F";
                    user_pregnancy_re.setVisibility(View.VISIBLE);
                    mView.setVisibility(View.VISIBLE);
                }
                Log.e("UHUserCenterFragment", sex);
                request();
            }
        });
        user_height.setPicker(user_height_Items);
        user_height.setLabels("CM");
        user_height.setCyclic(true);
        user_height.setTitle("请选择身高");
        user_height.setSelectOptions(user_height_Items.size() / 2);
        user_height.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                height = user_height_Items.get(options1).toString();
                user_height_exchange.setText(height + "CM");
                request();
                BMI();
            }
        });
        user_wight.setPicker(user_weight_Items);
        user_wight.setLabels("KG");
        user_wight.setTitle("请选择体重");
        user_wight.setCyclic(true);
        user_wight.setSelectOptions(user_weight_Items.size() / 2);
        user_wight.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                weight = user_weight_Items.get(options1).toString();
                user_weight_exchange.setText(weight + "KG");
                request();
                BMI();
            }
        });


        pvTime.setRange(calendar.get(Calendar.YEAR) - 120, calendar.get(Calendar.YEAR));
        pvTime.setTime(new Date());
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);

        //时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date1) {
                date = getTime(date1);
                user_birthday_exchange.setText(date);
                request();
            }
        });
    }

    private void BMI() {
        if (weight != null && height != null) {
            if (weight.equals("") || height.equals("")) {
                return;
            }
            double dWeight = Double.parseDouble(weight);
            double dHeight = Double.parseDouble(height);
            double v = dWeight / (dHeight * dHeight / 10000);
            DecimalFormat df = new DecimalFormat("#.00");
            String format = df.format(v);

            if (v > 18.5 && v < 24.99) {
                user_bmi_exchange.setText(format + "正常");
                user_bmi_exchange.setTextColor(Color.rgb(58, 206, 169));
            } else if (v > 25 && v < 28) {
                user_bmi_exchange.setText(format + "过重");
                user_bmi_exchange.setTextColor(Color.rgb(250, 85, 55));

            } else if (v > 28 && v < 32) {
                user_bmi_exchange.setText(format + "肥胖");
                user_bmi_exchange.setTextColor(Color.rgb(250, 85, 55));
            } else if (v > 32) {
                user_bmi_exchange.setText(format + "非常肥胖");
                user_bmi_exchange.setTextColor(Color.rgb(250, 85, 55));
            } else if (v < 18.5) {
                user_bmi_exchange.setText(format + "过低");
                user_bmi_exchange.setTextColor(Color.rgb(250, 85, 55));
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onResume() {
        super.onResume();
        isLogin = SharedPreUtils.getBoolean(getContext(), "is_Login", false);
        user_opinion_re.setOnClickListener(this);
        user_setting_re.setOnClickListener(this);
        user_disease_re.setOnClickListener(this);
        user_pregnancy_re.setOnClickListener(this);
        user_birthday_re.setOnClickListener(this);
        user_six_re.setOnClickListener(this);
        user_wight_re.setOnClickListener(this);
        user_height_re.setOnClickListener(this);
        BMI.setOnClickListener(this);
        user_pregnancy_exchange.setText(SharedPreUtils.getString(mActivity, "pregancy_time", "0") + "周");
        if (isLogin) {
            perDetails();
        } else {
            user_login.setText("点击登录");
            user_bmi_exchange.setText("");
            user_pregnancy_exchange.setText("");
            user_birthday_exchange.setText("");
            user_weight_exchange.setText("");
            user_height_exchange.setText("");
            user_sex_exchange.setText("");
        }


    }

    @SuppressLint("SetTextI18n")
    private void perDetails() {
        List<UserDataEntity> userDataEntities = userDataEntityDao.loadAll();
        if (userDataEntities != null && userDataEntities.size() > 0) {
            UserDataEntity userDataEntity = userDataEntities.get(0);
            name = userDataEntity.getName();
            date = userDataEntity.getBirthday();
            weight = userDataEntity.getWeight();
            sex = userDataEntity.getSex();
            height = userDataEntity.getHeight();
            tel = userDataEntity.getTelephone();
            user_login.setText(tel.substring(0, 3) + "****" + tel.substring(7));
            user_birthday_exchange.setText(date);
            if (("F").equals(sex)) {
                user_sex_exchange.setText("女");
                user_pregnancy_re.setVisibility(View.VISIBLE);
                mView.setVisibility(View.VISIBLE);
            } else {
                user_sex_exchange.setText("男");
                user_pregnancy_re.setVisibility(View.GONE);
                mView.setVisibility(View.GONE);
            }
            user_weight_exchange.setText(weight + "KG");
            user_height_exchange.setText(height + "CM");
            BMI();

        }

        final String user_token = SharedPreUtils.getString(mActivity, "user_token", null);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, UHBase.newUserInfoGet + "token=" + user_token, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
//                Log.e("UHUserCenterFragment", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.getString("code");
                    if (code.equals("0000")) {
                        Dataee dataee = gson.fromJson(response, Dataee.class);
                        Dataee.DataEntity data = dataee.getData();
                        if (data != null) {
                            Dataee.DataEntity dataEntity = data;
                            name = (String) dataEntity.getName();
                            cloudDate = dataEntity.getBirthday();
                            date = getTime(cloudDate);
                            weight = Double.toString((Double) dataEntity.getWeight());
                            int se = (int) dataEntity.getSex();
                            if (se == 1) {
                                sex = "F";
                            } else {
                                sex = "M";
                            }

                            height = Double.toString(dataEntity.getHeight());
                            tel = dataEntity.getPhone();
                            user_birthday_exchange.setText(date);
                            if (("F").equals(sex)) {
                                user_sex_exchange.setText("女");
                                user_pregnancy_re.setVisibility(View.VISIBLE);
                                mView.setVisibility(View.VISIBLE);
                            } else {
                                user_sex_exchange.setText("男");
                                user_pregnancy_re.setVisibility(View.GONE);
                                mView.setVisibility(View.GONE);

                            }
                            if (weight != null) {
                                user_weight_exchange.setText(weight + "KG");
                            }
                            if (height != null) {
                                user_height_exchange.setText(height + "CM");
                            }
                            user_login.setText(tel.substring(0, 3) + "****" + tel.substring(7));
                            BMI();
                            userDataEntityDao.deleteAll();
                            UserDataEntity userDataEntity = new UserDataEntity();
                            userDataEntity.setName(name);
                            userDataEntity.setBirthday(date);
                            userDataEntity.setWeight(weight);
                            userDataEntity.setSex(sex);
                            userDataEntity.setHeight(height);
                            userDataEntity.setTelephone(tel);
                            userDataEntityDao.insertOrReplace(userDataEntity);
                        }
                    } else if (code.equals("0005")) {

                    } else if (code.equals("0001")) {
                        Log.e("UHUserCenterFragment", "无数据");
                        putUserInformation(user_token);

                    } else if (code.equals("0004")) {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("UHUserCenterFragment", "error:" + error.toString());
            }
        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                String tel = SharedPreUtils.getString(mActivity, "user_tel", "");
//                params.put("telephone", tel);
//                return params;
//            }
        };
        volleySingleton.addQueue(stringRequest, "stringRequest");
    }

    /**
     * 添加用户信息
     *
     * @param user_token 用户的token
     */
    private void putUserInformation(String user_token) {
        try {
            String tel = SharedPreUtils.getString(mActivity, "user_tel", "");
            JSONObject jsonObject = new JSONObject();
            JSONObject userJson = new JSONObject();
            userJson.put("phone", tel);
            userJson.put("name", null);
            userJson.put("sex", 1);
            userJson.put("birthday", null);
            userJson.put("weight", null);
            userJson.put("height", null);
            userJson.put("bloodtype", null);
            jsonObject.put("isUpdate", 1);
            jsonObject.put("user", userJson);
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, UHBase.newUserInfoPut + "token=" + user_token, jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.e("UHUserCenterFragment", response.toString());
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Accept", "application/json");
                    headers.put("Content-Type", "application/json; charset=UTF-8");
                    return headers;
                }
            };
            volleySingleton.addQueue(jsonObjectRequest, "jsonObjectRequest");
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("UHUserCenterFragment", "e:" + e.toString());
        }

    }

//    public void request() {
//        StringRequest exchangeRe = new StringRequest(Request.Method.POST, UHBase.editDetails, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String response) {
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//
//            }
//        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                userDataEntityDao.deleteAll();
//                UserDataEntity userDataEntity = new UserDataEntity();
//                if (tel != null) {
//                    params.put("telephone", tel);
//                    userDataEntity.setTelephone(tel);
//                }
//                if (sex != null) {
//                    params.put("sex", sex);
//                    userDataEntity.setSex(sex);
//                }
//                if (date != null) {
//                    params.put("date", date);
//                    userDataEntity.setBirthday(date);
//                }
//                if (weight != null) {
//                    params.put("weight", weight);
//                    userDataEntity.setWeight(weight);
//                }
//                if (height != null) {
//                    params.put("height", height);
//                    userDataEntity.setHeight(height);
//                }
//                if (name != null) {
//                    params.put("name", name);
//                    userDataEntity.setName(name);
//                }
//                userDataEntityDao.insertOrReplace(userDataEntity);
//                return params;
//            }
//        };
//        volleySingleton.addQueue(exchangeRe, "exchangeRe");
//    }


    public void request() {
        String user_token = SharedPreUtils.getString(mActivity, "user_token", null);
        try {
            String tel = SharedPreUtils.getString(mActivity, "user_tel", "");
            JSONObject jsonObject = new JSONObject();
            JSONObject userJson = new JSONObject();
            userDataEntityDao.deleteAll();
            UserDataEntity userDataEntity = new UserDataEntity();
            if (tel != null) {
                userJson.put("phone", tel);
                userDataEntity.setTelephone(tel);
            }
            if (sex != null) {
                if (sex.equals("F")) {
                    userJson.put("sex", 1);
                } else {
                    userJson.put("sex", 0);
                }

                userDataEntity.setSex(sex);
            }
            if (date != null) {
                userJson.put("birthday", date);
                userDataEntity.setBirthday(date);
            }
            if (weight != null) {
                userJson.put("weight", weight);
                userDataEntity.setWeight(weight);
            }
            if (height != null) {
                userJson.put("height", height);
                userDataEntity.setHeight(height);
            }
            if (name != null) {
                userJson.put("name", name);
                userDataEntity.setName(name);
            }
            userDataEntityDao.insertOrReplace(userDataEntity);
            userJson.put("bloodtype", null);
            jsonObject.put("isUpdate", 1);
            jsonObject.put("user", userJson);

//            Log.e("UHUserCenterFragment", jsonObject.toString());

            JsonObjectRequest exchangeRe = new JsonObjectRequest(Request.Method.PUT, UHBase.newUserInfoEdit + "token=" + user_token, jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Accept", "application/json");
                    headers.put("Content-Type", "application/json; charset=UTF-8");
                    return headers;
                }

            };
            volleySingleton.addQueue(exchangeRe, "exchangeRe");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void setName(String name) {
        this.name = name;

    }

    @Override
    protected void initDestrory() {
        user_weight_Items.clear();
        user_sex_Items.clear();
        user_height_Items.clear();
    }

    @Override
    protected void initView() {
        isLogin = SharedPreUtils.getBoolean(getContext(), "is_Login", false);
        user_icon_re = (AutoRelativeLayout) view.findViewById(R.id.user_icon_re);
        user_disease_re = (AutoRelativeLayout) view.findViewById(R.id.user_disease_re);
        user_pregnancy_re = (AutoRelativeLayout) view.findViewById(R.id.user_pregnancy_re);
        user_birthday_re = (AutoRelativeLayout) view.findViewById(R.id.user_birthday_re);
        user_six_re = (AutoRelativeLayout) view.findViewById(R.id.user_six_re);
        BMI = (TextView) view.findViewById(R.id.BMI);
        user_wight_re = (AutoRelativeLayout) view.findViewById(R.id.user_wight_re);
        user_opinion_re = (AutoRelativeLayout) view.findViewById(R.id.user_opinion_re);
        user_height_re = (AutoRelativeLayout) view.findViewById(R.id.user_height_re);
        user_setting_re = (AutoRelativeLayout) view.findViewById(R.id.user_setting_re);
        user_pregnancy_exchange = (TextView) view.findViewById(R.id.user_pregnancy_exchange);
        user_birthday_exchange = (TextView) view.findViewById(R.id.user_birthday_exchange);
        user_sex_exchange = (TextView) view.findViewById(R.id.user_six_exchange);
        user_weight_exchange = (TextView) view.findViewById(R.id.user_wight_exchange);
        user_height_exchange = (TextView) view.findViewById(R.id.user_height_exchange);
        user_login = (TextView) view.findViewById(R.id.user_login);
        mView = view.findViewById(R.id.line_pregnancy);
        user_bmi_exchange = (TextView) view.findViewById(R.id.user_bmi_exchange);
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_usercentertwo, null);
        return view;
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (date == null) {
            return "";
        }
        return format.format(date);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_icon_re:
                if (isLogin) {
                    Intent intent = new Intent(mActivity, UHUserInformationActivity.class);
                    intent.putExtra("name", name);
                    intent.putExtra("tel", tel);
                    intent.putExtra("sex", sex);
                    intent.putExtra("date", date);
                    intent.putExtra("weight", weight);
                    intent.putExtra("height", height);
                    startActivityForResult(intent, 3);
                } else {
                    Intent intent = new Intent(mActivity, UHLogonActivity.class);
                    mActivity.startActivity(intent);
                }
                break;
            case R.id.user_disease_re:
                // 跳转到病史页面.
                if (!goToLogin()) {
                    startActivity(new Intent(mActivity, UHDiseaseHistoryActivity.class));
                }


                break;
            case R.id.user_pregnancy_re:
                if (!goToLogin()) {
                    //第二个参数为请求码，可以根据业务需求自己编号
                    startActivityForResult(new Intent(mActivity, UHUserPregnancyActivity.class), 1);
                }

                break;
            case R.id.user_birthday_re:
                if (!goToLogin()) {
                    pvTime.show();
                }

                break;
            case R.id.user_six_re:
                if (!goToLogin()) {
                    user_sex.show();
                }

                break;
            case R.id.user_wight_re:
                if (!goToLogin()) {
                    user_wight.show();
                }

                break;
            case R.id.user_height_re:
                if (!goToLogin()) {
                    user_height.show();
                }

                break;
            case R.id.exchange:
                if (!goToLogin()) {
                    request();
                }

                break;
            case R.id.user_opinion_re:
                Intent intent = new Intent(mActivity, UHFeedbackActivity.class);
                mActivity.startActivity(intent);
                break;

            case R.id.user_setting_re:
                startActivityForResult(new Intent(mActivity, UHSettingActivity.class), 2);
                break;
            case R.id.BMI:
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                builder.setMessage("这是体重相关的参数");
                builder.setPositiveButton("明白了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.show();
                break;
        }
    }

    private boolean goToLogin() {
        if (!isLogin) {
            Intent intent = new Intent(mActivity, UHLogonActivity.class);
            mActivity.startActivity(intent);
            return true;
        }
        return false;
    }


    public interface setTextView {
        void set(String s);
    }

    public void pregnancyChange(String date) {
        user_pregnancy_exchange.setText(date);

    }


}
